package ioc

import (
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/opentelemetry/tracing"
	"gorm.io/plugin/prometheus"
	"jk-time/webook/feed/dao"
	prome "jk-time/webook/pkg/gormx/callbacks"
)

func InitDB() *gorm.DB {
	user := viper.GetString(fmt.Sprintf("db.user"))
	password := viper.GetString(fmt.Sprintf("db.password"))
	host := viper.GetString(fmt.Sprintf("db.host"))
	dbs := viper.GetString(fmt.Sprintf("db.dbs"))

	sqlConfig := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc"+
		"=Local", user, password, host, dbs)
	db, err := gorm.Open(mysql.Open(sqlConfig))
	if err != nil {
		panic(err)
	}

	err = db.Use(prometheus.New(prometheus.Config{
		DBName:          "webook_feed",
		RefreshInterval: 15,
		StartServer:     false,
		MetricsCollector: []prometheus.MetricsCollector{
			&prometheus.MySQL{
				VariableNames: []string{"thread_running"},
			},
		},
	}))
	if err != nil {
		zap.L().Error("gorm监控失败:", zap.Error(err))
	}

	callback := prome.NewCallback(
		"feed_db",
		"webook",
		"gorm_op_time",
		"统计gorm的各项执行时间",
		"gorm_feed_1")

	err = db.Use(callback)
	if err != nil {
		zap.L().Error("gorm callback监控失败:", zap.Error(err))
	}

	db.Use(tracing.NewPlugin(tracing.WithDBName("webook"), tracing.WithQueryFormatter(func(query string) string {
		zap.L().Debug("", zap.String("query", query))
		return query
	}),
		//不要记录metrics
		tracing.WithoutMetrics(),
		//不要查询参数
		tracing.WithoutQueryVariables(),
	))

	err = dao.InitTables(db)
	if err != nil {
		panic(err)
	}
	return db
}
